package com.chatly.sentinel.demo.config;

import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * 处理服务层限流、熔断
 *
 * @author lihuazeng
 */
@RestControllerAdvice(annotations = RestController.class)
public class RestControllerExceptionAdvice {

    @ExceptionHandler(FlowException.class)
    public Map<String, Object> flowException(Exception e){
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        map.put("msg", "remote rpc flow control");
        return map;
    }


    @ExceptionHandler(RpcException.class)
    public Map<String, Object> rpcException(RpcException e){
        Map<String, Object> map = new HashMap<>();
        map.put("code", 500);
        if (e.getMessage().contains(DegradeException.class.getName())) {
            map.put("msg", "remote rpc circuit breaker");
        }
        map.put("code", 500);
        return map;
    }
}
